<?php
declare (strict_types = 1);

namespace app\api\middleware;

use app\common\model\Imapp;
use Closure;
use JetBrains\PhpStorm\NoReturn;
use think\Request;
use think\Response;

class ImAuth
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param Closure       $next
     * @return Response
     */
    #[NoReturn] public function handle(Request $request, Closure $next): Response
    {
        //
        $path = $request->pathinfo();
        try {
            $appid = explode('/',$path)[2];
            //获取imapp
            $imapp = Imapp::where('app_id',$appid)->findOrEmpty();
            if($imapp->isEmpty()){
                throw new \Exception('url地址无效');
            }
            $request->appId = $imapp->id;
        }catch (\Exception $e){
            return json([
                'code' => 401,
                'msg'  => 'url地址无效',
            ])->code(401);
        }
        return $next($request);
    }
}
